package com.godenwater.recv.server.yanyu;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.springframework.util.StringUtils;

import com.godenwater.yanyu.IMessageBody;
import com.godenwater.yanyu.IMessageHeader;
import com.godenwater.yanyu.YYMessage;
import com.godenwater.yanyu.YYMessageHeader;
import com.godenwater.yanyu.body.BaseBody;
import com.godenwater.yanyu.utils.ByteUtil;

public class ClientDataDecoder implements ProtocolDecoder {
	private static final AttributeKey BUF_BYTE = new AttributeKey(
			ClientDataDecoder.class, "BUF_KEY");

	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception {
		// TODO Auto-generated method stub
		try {

			System.out.println(">>> YfClientDataDecoder decode " + StringUtils.trimAllWhitespace(in.getHexDump()));

			IoBuffer buffer = null;
			byte[] buf = (byte[]) session.getAttribute(BUF_BYTE);
			if (buf == null) {
				// System.out.println("没有尚未处理的数据");
				buffer = in;
			} else {
				// System.out.println("合并尚未处理的数据");
				buffer = IoBuffer.allocate(buf.length + in.remaining());
				buffer.setAutoExpand(true);
				buffer.put(buf);
				buffer.put(in);
				buffer.flip();
			}

			// while (buffer.remaining() >= 0) {// 循环处理数据包
			// //
			// int dataLen = buffer.getInt(buffer.position());
			// byte[] b = new byte[dataLen];
			// buffer.get(b);
			// SMPPPacket pak = null;
			// int id = -1;
			// id = SMPPIO.bytesToInt(b, 4, 4);
			// pak = PacketFactory.newInstance(id);
			// if (pak != null) {
			// pak.readFrom(b, 0);
			// out.write(pak);
			// }

			IMessageHeader header = new YYMessageHeader();
			byte[] startBit = new byte[1];
			buffer.get(startBit);
			header.setStartBit(startBit);

			// 下行的，遥测站地址在前
			byte[] stationAddr = new byte[header.getStationAddrLen()];
			buffer.get(stationAddr);
			header.setStationAddr(stationAddr);

			// 下行的，中心站地址在后
			byte[] centerAddr = new byte[header.getCenterAddrLen()];
			buffer.get(centerAddr);
			header.setCenterAddr(centerAddr);

			byte[] funcCode = new byte[header.getFuncCodeLen()];
			buffer.get(funcCode);
			header.setFuncCode(funcCode);

			byte[] bodySize = new byte[header.getBodySizeLen()];
			buffer.get(bodySize);
			header.setBodySize(bodySize);

			// 转换报文中的上下行标识及报文长度
			int bodyLengthLen = ByteUtil.bytesToUbyte(bodySize);// 需要考虑拆分字节;
			byte[] bodyContent = new byte[bodyLengthLen - 3];// 根据前面header的内容来获取长度
			buffer.get(bodyContent);

			// 终止符
			byte[] eof = new byte[1];
			buffer.get(eof);

			// 校验码
			byte[] crc = new byte[2];
			buffer.get(crc);

			// 组装消息
			YYMessage message = new YYMessage();
			message.setHeader(header);

			// 根据功能码，构建body体
			IMessageBody body  = new BaseBody();
			body.setContents(bodyContent);
			message.setBody(body);

			message.setEOF(eof[0]);
			message.setCRC(crc);

			out.write(message);

			// }
			if (buffer.hasRemaining()) {// 如果有剩余的数据，则放入Session中
				byte[] tmpb = new byte[buffer.remaining()];
				buffer.get(tmpb);
				session.setAttribute(BUF_BYTE, tmpb);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private int parseLength(byte[] bodyLen) {
		byte A1 = (byte) (bodyLen[0] & 0x0f);
		byte A2 = bodyLen[1];
		return ByteUtil.bytesToUshort(new byte[] { A1, A2 });
	}

	public void dispose(IoSession session) throws Exception {
		// TODO Auto-generated method stub

	}

	public void finishDecode(IoSession session, ProtocolDecoderOutput out)
			throws Exception {
		// TODO Auto-generated method stub

	}

	public void parseMessage() {

	}

}
